export function base64ToFile(base64String) {
  // console.log('--------base64')
  // console.log(base64String)
  let arr = base64String.split(",");
  const byteCharacters = atob(arr[1]);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], { type: "application/octet-stream" });
  const file = new File([blob], `${new Date().getTime()}.png`);
  return file;
}

//脉诊仪相关
//判断蓝牙是否连接
const checkBleConnect = () => {
  if (!window.myDeviceInfo) {
    return {
      suc: false,
      msg: "脉诊仪未连接",
    };
  }
  return {
    suc: true,
    msg: "OK",
  };
};

const uuid = "00001000-0000-1000-8000-00805f9b34fb";
const Wuuid = "00001001-0000-1000-8000-00805f9b34fb";
const Ruuid = "00001002-0000-1000-8000-00805f9b34fb";

let deviceInfo;
//搜索脉诊仪
export const searchDevice = async (callback) => {
  let device = await navigator.bluetooth.requestDevice({
    filters: [
      {
        // namePrefix: "BYS",
        services: [uuid],
      },
    ],
    // optionalServices: [uuid]
    // filters: [{
    //   name: 'Bayes003',
    // //   services: [uuid]
    // }],
    optionalServices: [uuid],
    acceptAllDevices: false,
    // acceptAllDevices:true
  });
  deviceInfo = device;
  let res = await connectDevice(callback);
  return res;
  // deviceInfo = device;
  //     console.log(device);
  //     window.myDeviceInfo = device;
  //     // console.dir(device);
  //     // 在此处实现设备调用
  //     try {
  //       await connectDevice(callback);
  //     } catch (e) {
  //     } finally {
  //       //   loading.close()
  //     }
  // .then(async function (device) {

  // })
  // .catch(function (error) {
  //   console.log(error);
  //   // ElMessage({
  //   //   message: error,
  //   //   type: 'warning',
  //   // })
  //   // loading.close()
  // });
};

//获取已配对设备
export const getDevice = (callback) => {
  if (!navigator.bluetooth.getDevices) {
    return searchDevice(callback);
  }
  navigator.bluetooth
    .getDevices()
    .then((devices) => {
      // 遍历已配对的设备列表，找到目标设备进行连接
      devices.forEach((device) => {
        console.log(device);
        if (device.name.indexOf("BYS") !== -1) {
          deviceInfo = device;
          window.myDeviceInfo = device;
          connectDevice(callback);
          // device.gatt.connect()
          //   .then(server => {
          //     console.log('设备已连接:', server);
          //   })
          //   .catch(error => {
          //     console.error('连接设备时出错:', error);
          //   });
        }
      });
    })
    .catch((error) => {
      console.error("获取已配对设备时出错:", error);
    });
};

let charService;
let charRService;
//连接脉诊仪
const connectDevice = async (callback) => {
  let res = await deviceInfo.gatt.connect();
  console.log("连接完成",res);

  let deviceService = await deviceInfo.gatt.getPrimaryService(uuid);
  console.log("获取服务完成");

  //return console.log(deviceService)
  charService = await deviceService.getCharacteristic(Wuuid);
  //console.log(charService)
  console.log("获取特征完成");

  charRService = await deviceService.getCharacteristic(Ruuid);
  console.log("读初始化完成");
  //console.log(charRService)
  return initNotify(callback);
};

//接收回调信息
const initNotify = async (callback) => {
  charRService.addEventListener(
    "characteristicvaluechanged",
    handleCharacteristicValueChanged
  );
  charRService.startNotifications();
  callback();
  return true;
};

window.testRes = "";
//   let loading;

function handleCharacteristicValueChanged(event) {
  console.log("开始处理数据");
  let value = event.target.value;
  if (value.byteLength !== 13) {
    console.log('数据不符合',hexToStr(value.buffer))
    return;
  }
  value = hexToStr(value.buffer);
  testRes += value;
  if (value.slice(0, 8) == "aaaaf508") {
    //左手脉数据接受完成,改变流程状态
    console.log("处理数据完成");
    otherCallback();
    // console.log("脉诊完成", window.testRes);
  }
}

//设置完成通知
let otherCallback = () => {};

//向脉诊仪发送数据
export const send2Device = (callback) => {
  window.testRes = "";
  let value = strToHex("fa0d0a");
  charService.writeValueWithResponse(value).then((res) => {
    console.log("写入回调数据");
    otherCallback = callback;
    //开始左手脉诊
    // if (maizhenStatus.value === 1) {
    //   actionLeftHandTest()
    // } else if (maizhenStatus.value === 3) {
    //   actionRightHandTest()
    // }
  });
};

//字符串转16进制
function strToHex(str) {
  //str = '7301aa01001e6f'
  let typedArray = new Uint8Array(
    str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    })
  );

  let buffer = typedArray.buffer;
  return buffer;
}

//16进制转字符串
function hexToStr(buffer) {
  let hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
    return ("00" + bit.toString(16)).slice(-2);
  });
  return hexArr.join("");
}
